import { useCallback, useEffect, useImperativeHandle, useState } from 'react';
import { getModelList } from '../services';
import { Input, Table, Empty } from 'antd';
import { getMessage, TextWidget } from '@inbiz/react';
import styles from '../index.less';
import { InbizIcon } from '@inbiz/utils';

const ModelPicker = (props: any) => {
  const { appInfo } = props;
  // model数据请求loading
  const [loadding, $loadding] = useState<boolean>(false);
  // model数据
  const [modelData, $modelData] = useState<object[]>([]);
  // 筛选后model数据
  const [modelFilterData, $modelFilterData] = useState<object[]>([]);
  // 选中的modelkey
  const [selectedRowKeys, $selectedRowKeys] = useState<string[]>([]);

  useImperativeHandle(props.refs, () => ({
    submit: submit,
  }));

  // 请求model数据
  useEffect(() => {
    $loadding(true);
    getModelList(appInfo)
      .then((res) => {
        if (Array.isArray(res.List)) {
          let arr = [...props.setSelect];
          let list = res.List.filter(
            (item: any) => arr.indexOf(item.ModelKey) < 0,
          );
          $modelData(list);
          $modelFilterData(list);
        } else {
          $modelData([]);
          $modelFilterData([]);
        }
        $loadding(false);
      })
      .catch(() => {
        $modelData([]);
        $modelFilterData([]);
        $loadding(false);
      });
  }, [props.setSelect]);

  // 确定选中
  const submit = () => {
    const data: any[] = [];
    selectedRowKeys.map((item) => {
      let arr = modelData.filter((val: any) => val.ModelKey === item);
      arr[0] && data.push(arr[0]);
    });
    return data;
  };

  // 模型数据筛选
  const modelFilter = useCallback(
    (e) => {
      let arr = modelData.filter(
        (item: any) => item.Name.indexOf(e.target.value) > -1,
      );
      $modelFilterData(arr);
    },
    [modelData],
  );

  // 多选点击行选择/取消
  const rowClick = useCallback(
    (record: any) => {
      if (Array.isArray(selectedRowKeys)) {
        let select = [...selectedRowKeys];
        if (select?.indexOf(record.ModelKey) > -1) {
          let idx = select?.indexOf(record.ModelKey);
          if (idx || idx === 0) select?.splice(idx, 1);
        } else {
          select.push(record.ModelKey);
        }
        $selectedRowKeys(select);
        props.setTotal && props.setTotal(select.length);
      }
    },
    [selectedRowKeys],
  );

  // 复选框配置
  const rowSelection = {
    selectedRowKeys,
    preserveSelectedRowKeys: true,
    onChange: (selectedRowKeys: any) => {
      $selectedRowKeys(selectedRowKeys);
      props.setTotal && props.setTotal(selectedRowKeys.length);
    },
  };

  // 表格字段配置
  const modelColumns = [
    {
      title: getMessage('PermissionConfig.model_name'), // 模型名称
      dataIndex: 'Name',
      key: 'Name',
      width: 714,
    },
  ];

  return (
    <>
      <div className={styles['inbiz-component-permission-config-modal-picker']}>
        <Input
          placeholder={getMessage(
            'PermissionConfig.placeholder_input_key_word',
          )} // 请输入关键词
          suffix={<InbizIcon type="icon-ic-sousuo" style={{ color: '#999' }} />}
          onChange={modelFilter}
          allowClear
        />
        <Table
          columns={modelColumns}
          dataSource={modelFilterData}
          loading={loadding}
          rowKey="ModelKey"
          rowSelection={rowSelection}
          pagination={false}
          scroll={{ y: 274 }}
          onRow={(record: any) => {
            return {
              onClick: (e) => {
                e.stopPropagation();
                rowClick(record);
              },
            };
          }}
          locale={{
            emptyText: (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={<TextWidget>PermissionConfig.no_data</TextWidget>}
              />
            ),
          }}
        />
      </div>
    </>
  );
};

export default ModelPicker;
